<template>
	<view class="time-slot">
		<view :style="[timeSlotStyle]">
			<view class="time-slot__content">
				<view class="time-slot__content-item" :style="[timeSlotItemStyle]" v-for="(item,index) in times" :key="index">
					<view class="time-slot__content-box" @click="onClick(item,index)" :style="[activeTimeSlot(item, index)]"></view>
				</view>
			</view>
			<view class="time-slot__text">
				<view class="time-slot__text-item" :style="[timeSlotTextItemStyle]" v-for="(item,index) in times" :key="index">
					<view class="time-slot__text-box" :style="[timeSlotTextBoxStyle]" v-if="index!==times.length-1">{{timeText(item)}}</view>
					<view class="time-slot__text-box" :style="[timeSlotItemTextEndStyle]" v-if="index===times.length-1">{{timeStringToNumber(endTime, true)}}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "itu-time-slot",
		props: {
			// 开始时间
			startTime: {
				type: [Number, String],
				default: 8
			},
			// 结束时间
			endTime: {
				type: [Number, String],
				default: 20
			},
			// 间隔时间（分钟）
			timeSlot: {
				type: Number,
				default: 15
			},
			// 默认背景颜色
			defaultColor: String,
			// 禁用背景颜色
			disabledColor: String,
			// 选中背景颜色
			activeColor: String,
			//禁用时间
			disabledTime: {
				type: Array,
				default: () => {
					return []
				}
			},
			// 选中时间
			activeTime: {
				type: Array,
				default: () => {
					return []
				}
			},
			// 刻度
			mark: {
				type: Boolean,
				default: true
			},
			// 模式，可选：hour/minute
			mode: {
				type: String,
				default: 'hour'
			},
			// 字体大小
			fontSize: {
				type: String,
				default: '26rpx'
			},
			// 高度
			height: {
				type: Number,
				default: 26
			}
		},
		data() {
			return {
				times: [],
				innerDefaultColor: '',
				innerDisabledColor: '',
				innerActiveColor: '',
				innerTimeSlot: 0,
				innerDisabledTime: [], //已禁用时间
				innerActiveTime: [], //已选中时间
			};
		},
		computed: {
			timeSlotStyle() {
				const timeSlotHeight = uni.$itu.rpx2px(this.height)
				return {
					'--itu-time-slot-height': `${timeSlotHeight}px`
				}
			},
			timeSlotItemStyle() {
				const width = `${(100/this.times.length.toFixed(2))}%`;
				return {
					width: width,
				}
			},
			timeSlotTextItemStyle() {
				const width = `${(100/this.times.length).toFixed(2)}%`;
				return {
					width: width,
					fontSize: this.fontSize
				}
			},
			timeSlotTextBoxStyle() {
				const width = `${((100/this.times.length)/2).toFixed(2)}%`;
				return {
					marginLeft: '-100%',
				}
			},
			timeSlotItemTextEndStyle() {
				const width = `${((100/this.times.length)/2).toFixed(2)}%`;
				return {
					textAlign: 'right',
					marginRight: '-12rpx',
					fontSize: this.fontSize
				}
			}
		},
		watch: {
			activeTime: {
				handler() {
					let innerActiveTime = []
					this.activeTime.forEach(item => {
						innerActiveTime.push(this.timeToNumber(item))
					})
					this.innerActiveTime = innerActiveTime
				},
				deep: true,
				immediate: true
			},
			disabledTime: {
				handler() {
					let innerDisabledTime = []
					this.disabledTime.forEach(item => {
						innerDisabledTime.push(this.timeToNumber(item))
					})
					this.innerDisabledTime = innerDisabledTime
				},
				deep: true,
				immediate: true
			}
		},
		mounted() {
			this.innerTimeSlot = this.timeSlot / 60
			this.innerActiveColor = this.activeColor || this.$itu.color.primary
			this.innerDefaultColor = this.defaultColor || this.$itu.color.primaryLight
			this.innerDisabledColor = this.disabledColor || this.$itu.color.primaryDisabled
			const startTime = this.timeStringToNumber(this.startTime)
			const endTime = this.timeStringToNumber(this.endTime, true)
			this.times = this.generateTimeSlots(startTime, endTime, this.innerTimeSlot)
		},
		methods: {
			timeStringToNumber(time, ceil = false) {
				if (typeof time === 'string') {
					if(!isNaN(time)){
						return Number(time)
					}else{
						const timeString = time;
						// 使用冒号分割时间字符串
						const timeParts = timeString?.split(":");
						// 如果分割后的数组长度小于等于1，返回0
						if (timeParts.length <= 1) return 0;
						// 转换时间字符串的第一个部分为整数
						let result = parseInt(timeParts[0], 10);
						if (ceil && timeParts.length > 1 && parseInt(timeParts[1]) !== 0) {
							result = result+1;
						}
						return result;
					}
				} else return time;
			},
			onClick(item, index) {
				this.$emit("click", { value: item, index, time: this.numberToTime(item) })
			},
			timeText(item) {
				if (this.mode === 'hour') {
					if (/^\d+$/.test(item) && !isNaN(parseInt(item, 10))) return item
					else return ""
				} else return item
			},
			activeTimeSlot(item, index) {
				let style = { background: this.innerDefaultColor }
				if (this.innerDisabledTime.includes(Number(item))) {
					style.background = this.innerDisabledColor
					if (this.mark) style.borderRight = "1rpx solid #FFFFFF"
				}
				if (this.innerActiveTime.includes(Number(item))) {
					style.background = this.innerActiveColor
					if (this.mark) style.borderRight = "1rpx solid #FFFFFF"
				}
				return style
			},
			timeToNumber(timeString) {
				const [hour, minute] = timeString.split(':').map(parseFloat);
				return hour + minute / 60;
			},
			numberToTime(number) {
				const hour = Math.floor(number);
				const minute = Math.round((number - hour) * 60);
				return `${hour}:${minute < 10 ? '0' : ''}${minute}`;
			},
			generateTimeSlots(startTime, endTime, timeSlot) {
				const slots = [];
				let currentTime = startTime;
				while (currentTime < endTime) {
					slots.push(currentTime);
					currentTime += timeSlot;
				}
				return slots;
			}
		}
	}
</script>

<style lang="scss">
	.time-slot {
		margin: 0 auto;

		&__text {
			display: flex;
			height: 40rpx;
			margin-top: -10rpx;

			&-item {
				display: inline-block;
				text-align: center;
			}

			&-box {
				height: var(--itu-time-slot-height);
				transform: scale(.8);
			}
		}

		&__content {

			&-item {
				display: inline-block;
			}

			&-box {
				height: var(--itu-time-slot-height);
			}
		}
	}
</style>